package com.apply.config.web;

import com.alibaba.fastjson.JSON;
import com.apply.config.Results;
import com.apply.entity.SysUser;
import com.apply.service.AuthService;
import org.apache.commons.lang3.StringUtils;
import org.apache.commons.lang3.Validate;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.web.servlet.handler.HandlerInterceptorAdapter;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.PrintWriter;

/**
 * @author tianp
 */
@Component
public class SidAuthInterceptor extends HandlerInterceptorAdapter {
    @Autowired
    private AuthService authService;

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        String token = request.getHeader("sid");
        Validate.notNull(token, "令牌不能为空！");
        SysUser sysUserInfo = authService.getSysUserInfo(token);
        if (sysUserInfo == null || StringUtils.isEmpty(sysUserInfo.getUsername())) {
            resultError(response);
            return false;
        }
        SidAuthContext.set(sysUserInfo);
        return true;
    }


    private void resultError(HttpServletResponse response) throws IOException {
        PrintWriter out = response.getWriter();
        out.println(JSON.toJSONString(Results.error(403, "user not login")));
        out.flush();
        out.close();
    }

    @Override
    public void afterCompletion(
            HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex)
            throws Exception {
        SidAuthContext.remove();
    }
}